package com.scau.phr.business.medicine.controller;
import com.scau.phr.business.auth.anno.Permitting;
import com.scau.phr.business.auth.domain.Role;
import com.scau.phr.business.medicine.service.MedicineService;
import com.scau.phr.common.exceptions.ErrorCode;
import com.scau.phr.domain.entity.Medicine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 医药接口控制器
 * @author yuzhiyi
 * @date 2018/7/29 14:45
 */
@RestController
@RequestMapping("/medicine")
public class MedicineController {
    @Autowired
    private MedicineService medicineService;

    /**
     * 添加药品信息
     * 使用@Valid可以自动校验相关字段，不需要使用BindingResult
     */
    @PostMapping(value = "/add")
    public Object addMedicine(@Valid Medicine medicine){
       return medicineService.addMedicine(medicine);
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Object deleteMedicine(@RequestParam("id") Integer id){
        if (id == null){
            return ErrorCode.PARAMS_ERROR;
        }
        return medicineService.deleteMedicine(id);
    }

    @Permitting(Role.REGISTER_USER)
    @RequestMapping(value = "/get",method = RequestMethod.GET)
    public Object getMedicineInfo(@RequestParam("id")Integer id){
        return medicineService.getMedicineById(id);
    }

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public Object searchMedicineByName(@RequestParam("name")String name,
                                        @RequestParam(value = "page",required = false)Integer page ){
        if (name == null){
            return ErrorCode.PARAMS_ERROR;
        }
        return medicineService.queryMedicineByNameWithPage(name,page);
    }

    @RequestMapping(value = "/getName",method = RequestMethod.GET)
    public Object getMedicineName(@RequestParam("page")Integer page){
        return medicineService.listMedicineName(page);
    }

    @PostMapping(value = "/update")
    public Object updateMedicine(Medicine medicine, BindingResult bindingResult){
        if (medicine.getId() == null){
            return ErrorCode.PARAMS_ERROR;
        }
        return medicineService.updateMedicine(medicine);
    }






}
